package practise.hibernate.dao.impl;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import practise.hibernate.dao.PersonDao;
import practise.hibernate.persistence.Address;
import practise.hibernate.persistence.Person;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Service("personDao")
@Repository
@Transactional
public class PersonDaoImpl implements PersonDao {
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional(readOnly = true)
    public List<Person> findAllPersons(){
        final Query query = entityManager.createQuery("select t from person t ");
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Person> findPersonByName(String name){
        final Query query = entityManager.createQuery("select distinct t from person t where t.personName.firstName = :name ");
        query.setParameter("name" , name);
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteAddress(int id){
        entityManager.remove(entityManager.find(Person.class , id));
    }

    @Override
    @Transactional(readOnly = false )
    public Person merge(Person person){
        return entityManager.merge(person);
    }
}
